package com.wdh.kjs.manager;

import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.memory.impl.UsingFreqLimitedMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.wdh.kjs.R;

/**
 * Created by codingWw on 2016/3/8.
 */
public class ImageLoadManager {

    private static ImageLoadManager instance;
    private Context context;
    private DisplayImageOptions displayImageOptions;

    private ImageLoadManager(Context context) {
        this.context = context;
        initImageLoader();
    }

    public synchronized static ImageLoadManager getInstance(Context context) {
        if (instance == null) {
            instance = new ImageLoadManager(context);
        }
        return  instance;
    }

    //初始化ImageLoader
    private void initImageLoader() {
        ImageLoaderConfiguration imageLoaderConfiguration = new ImageLoaderConfiguration
                .Builder(context.getApplicationContext())
                .memoryCacheExtraOptions(480, 800)
                .threadPoolSize(10)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
                .memoryCacheSize(2 * 1024 * 1024)
                .diskCacheSize(50 * 1024 * 1024)
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .diskCacheFileCount(200)
                .defaultDisplayImageOptions(DisplayImageOptions.createSimple())
                .writeDebugLogs()
                .build();
        ImageLoader.getInstance().init(imageLoaderConfiguration);

        displayImageOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .showImageOnFail(R.mipmap.pic_load_failed)
                .build();
    }

    public void displayImage(String url, ImageView view) {
        if (TextUtils.isEmpty(url))
            return;
        ImageLoader.getInstance().displayImage(url, view, displayImageOptions);
    }

    public void  loadImage(String url, ImageLoadingListener listener) {
        if (TextUtils.isEmpty(url))
            return;
        ImageLoader.getInstance().loadImage(url, displayImageOptions, listener);
    }

    public Bitmap loadImageSyn(String url) {
        if (TextUtils.isEmpty(url))
            return null;
        return ImageLoader.getInstance().loadImageSync(url, displayImageOptions);
    }
}
